<template>
	<div style="width: 100%;">
		<div style="width: 100%;color: orange;margin-bottom: 2px;">
			<slot></slot>
		</div>
		<el-header class="nopadding" style="height: 50px;margin-top: -6px;padding: 0px !important;">
			<el-input size="small" v-model="filterText" :placeholder="this.$t('common.search_tip')" clearable
					  class="exSearchTree_search_tip"/>
		</el-header>
		<el-main class="nopadding">
			<div style="float:left;width: 100%;background-color: rgba(82,81,81,0.05);">
				<div
					style="float:left;height: 30px;padding-left: 20px;line-height: 30px;">
					名称
				</div>
				<div
					style="float:right;width: 120px;height: 30px;line-height: 30px;border-left: 1px solid rgba(82,81,81,0.05);padding-left: 20px;">
					编码
				</div>
			</div>
			<div style="float:left;width: 100%;height: 300px;" v-loading="loading">
				<el-tree
					ref="tree"
					class="exSearchTree_tree_main"
					:data="tree_data"
					:props="defaultProps"
					:load="loadNode"
					:check-strictly="true"
					lazy
					:node-key="nodeKey"
					highlight-current
					show-checkbox
					:default-expanded-keys="['0000000']"
					accordion
					:expand-on-click-node="false"
					:filter-node-method="filterNode"
					@check-change="handleCheckChange"
					@check="handleCheck"
					icon="el-icon-caret-right">

					<template #default="{ node, data }">
					<span class="custom-tree-node">
						<span style="float: left;">{{ node.label }}</span>
						<span style="float:right;width: 100px;text-align: left;">
						  {{ data.code }}
						</span>
				    </span>
					</template>
				</el-tree>
			</div>
		</el-main>
	</div>
</template>

<script>

import {watch} from "vue";

export default {
	name: "exTreeTable",
	props: {
		tree_class: {type: String, default: 'filter-tree'},
		treeApi: {type: Object, default: {}},//数据加载的url
		param: {type: Object, default: null},//搜索参数
		relEntity: {type: Array, default: []},//实体对象
		relEntityName: {type: String, default: null},//实体对象名称
		name: {type: String, default: null},//关联对象的实体名称
		nodeKey: {type: String, default: 'id'},
		relEntityId: {type: String, default: ''},
		stripe: {type: Boolean, default: true},
		border: {type: Boolean, default: true},
		selection: {type: Boolean, default: true},
		defaultExpandAll: {type: Boolean, default: false},
		height: {type: Number, default: null},
		maxHeight: {type: Number, default: null},
		filterDataList: {type: Array, default: null},
		tableLayout: {type: String, default: 'fixed'},//fixed,autos
		size: {type: String, default: "default"},//large / default /small
		columns: {type: Array, default: null},
	},

	components: {},
	data() {
		return {
			loading: false,
			defaultProps: {
				children: 'children',
				label: 'label',
				isLeaf: this.isLeaf,
			},
			filterText: null,
			tree_data: [],
			ori_data: [],
			entity: this.$store.state.entity,
			oldEntity: {},
			entityName: this.name,
			relMap: {},
			fommaterData : 0,
			checkIds: [],
		}
	},
	watch: {
		filterText(newVal) {
			this.$refs.tree.filter(newVal);
		},
		filterDataList(newVal) {
			this.fommaterData = 1;
			this.refresh();
		},
		entity: {
			handler(val) {
				for (let key in val) {
					if (key === this.treeApi.storeName) {
						if (!this.oldEntity[key] || this.oldEntity[key].count !== val[key].count) {
							this.refresh({toServer: true});
						}
					}
				}
				this.oldEntity = this.$TOOL.objCopy(val);
			},
			deep: true,
			immediate: false,
		}
	},
	computed: {},
	created() {
	},
	mounted() {
		this.refresh();
	},
	methods: {
		isLeaf(data, node) {
			return data.isLeaf;
		},
		loadNode(node, resolve) {
			if (node.level === 0) {
				resolve(this.tree_data);
			} else {
				let data = [];
				if (node.data.levelCode === "0000000") {
					data = this.ori_data
					node.data.children = data;
				} else {
					data = node.data.children;
				}
				let finalData = [];
				data.forEach(item => {
					item.isLeaf = !item.children || item.children.length === 0;
					finalData.push(item);
				});
				resolve(finalData);
			}
		},
		setCheckedKeys(checkKeys) {
			if (this.$refs && this.$refs.tree) {
				this.$refs.tree.setCheckedKeys(checkKeys);
			}
			if(checkKeys.length > 0){
				this.setRelMaps();
			}
		},
		setDisabledKeys(nodeData) {
			if(!nodeData){
				return;
			}
			nodeData.forEach(item => {
				item.disabled = "1";
				if (item.children && item.children.length > 0) {
					this.setDisabledKeys(item.children);
				}
			})
		},
		setEnabledKeys(nodeData,filterDataList) {
			if(!nodeData){
				return;
			}
			nodeData.forEach(item => {
				filterDataList.find(filterItem => {
					if(filterItem === item.id){
						item.disabled = "";
					}
				})
				if (item.children && item.children.length > 0) {
					this.setEnabledKeys(item.children,filterDataList);
				}
			})
		},
		filterNode(value, data) {
			if (!value) return true;
			return (data.label && data.label.includes(value)) || (data.code && data.code.includes(value));
		},
		handleCheckChange(data, checked, indeterminate) {
			// this.checkIds = this.checkIds.filter(id => id !== data.id);
			// console.log(this.checkIds)
			// if (checked) {
			// 	this.checkIds.push(data.id);
			// 	console.log(this.checkIds)
			// }
			// console.log("handleCheckChange", data, checked);
			// //设置映射关系
			// if (!this.relMap[this.entityName]) {
			// 	this.relMap[this.entityName] = [];
			// }
			// this.relMap[this.entityName] = this.$refs.tree.getCheckedKeys();
			// //赋值
			// if (this.relEntity) {
			// 	if (!this.relEntity.relMaps) {
			// 		this.relEntity.relMaps = {};
			// 	}
			// 	this.relEntity.relMaps[this.entityName] = {};
			// 	//重新赋值新数据
			// 	Object.assign(this.relEntity.relMaps, this.relMap);
			// }
		},
		handleCheck(data, checkData) {
			// console.log("handleCheck", data, checkData);
			//判断当前节点是否被选中
			let checked = true;
			if (checkData.checkedKeys.filter(key => key === data[this.nodeKey]).length === 0) {
				checked = false;
			}
			//获取当前节点下所有子节点的id
			let childrenIds = [];
			if (data.children) {
				childrenIds = this.childrenKeys(data.children);
			}
			//把当前节点的id也加入到子节点id的集合中
			childrenIds.push(data[this.nodeKey]);

			//合并原始勾选的id和当前节点下所有的子节点的id,并使用set去重
			let setKeys = new Set([...this.checkIds, ...childrenIds]);

			//当前节点未选中时,删除当前节点所有的子节点
			if (!checked) {
				childrenIds.forEach(item => {
					setKeys.delete(item);
				});
			}
			//set中剩下的id为当前真实选中的所在id,重新赋值给checkIds
			this.checkIds = Array.from(setKeys);
			//("当前选中数量  " + this.checkIds.length,this.checkIds);
			//重新设置树的勾选状态
			this.setCheckedKeys(this.checkIds);

		},
		setRelMaps(){
			//赋值
			if(this.relEntity){
				this.relEntity.splice(0,this.relEntity.length);
			}
			this.checkIds.forEach(item =>{
				this.relEntity.push(item);
			});
		},
		childrenKeys(children) {
			let keys = [];
			if (Array.isArray(children)) {
				children.forEach(item => {
					if(item.disabled != "1"){
						keys.push(item[this.nodeKey]);
					}
					if (item.children) {
						let childrenKeys = this.childrenKeys(item.children);
						childrenKeys.forEach(key => {
							keys.push(key);
						});
					}
				})
			}
			return keys;
		},
		async refresh(data) {
			if (!this.treeApi) {
				return;
			}
			this.loading = true;
			let root = {};
			root.id = "0000000";
			root.levelCode = "0000000";
			root.code = "0000000";
			root.parentLevelCode = root.levelCode;
			root.pathCode = root.parentLevelCode + "," + root.levelCode;
			root.label = "全部";
			root.icon = "el-icon-folder"
			root.children = [];
			root.isEnabled = "1";
			let queryParams = {parentLevelCode: root.levelCode};
			//引入自定义参数
			if (data) {
				queryParams = Object.assign(queryParams, data);
			}
			if (this.param) {
				queryParams = Object.assign(queryParams, this.param);
			}
			//请求数据加载
			let result = await this.$cache.tree.reload(this.treeApi.storeName, queryParams);
			if (result) {
				//如果当前关系表的实体名称为空,则从获取的数据中获取默认名称
				if (!this.entityName) {
					result.forEach(item => {
						if (!this.entityName) {
							this.entityName = item.entityName;
						}
					});
				}
				//树形数据赋值给原始数据,做备份使用
				//设置禁用
				this.setDisabledKeys(result);
				this.ori_data = result;
				//设置root节点是否为叶子节点
				root.isLeaf = this.ori_data.length === 0;
				//设置树的数据
				this.tree_data = [root];
			}
			//查询实体之间已存在的映射关系
			this.checkIds = [];
			if (this.relEntityName && this.relEntityId && this.fommaterData == 0) {
				let queryDto = {
					firstEntity: this.relEntityName,
					firstEntityId: this.relEntityId,
					secondEntity: this.entityName,
				};
				let rsp = await this.$API.system.relMap.load.post(queryDto);
				if (rsp.code === 2000 && Array.isArray(rsp.data)) {
					if(this.filterDataList){
						this.filterDataList.splice(0,this.filterDataList.length);
					}
					rsp.data.forEach(item => {
						this.filterDataList.push(item.secondEntityId);
					});
				}
			}
			//设置为可用状态
			if(this.filterDataList.length){
				root.disabled = "";
				this.setEnabledKeys(this.ori_data,this.filterDataList);
			}else{
				root.disabled = "1";
			}
			if(this.fommaterData == 0){
				if(this.relEntity){
					this.relEntity.forEach(item =>{
						this.checkIds.push(item);
					})
				}else{
					this.filterDataList.forEach(item =>{
						this.checkIds.push(item);
					})
				}
			}else{
				this.filterDataList.forEach(item =>{
					this.checkIds.push(item);
				})
				this.checkIds = this.filterDataList;
			}
			//设置默认勾选的节点
			this.setCheckedKeys(this.checkIds);
			this.loading = false;
		},
	}
}
</script>

<style scoped>

/*树组件样式*/
::v-deep(.exSearchTree_search_tip) {
	width: 100%;
	line-height: 35px;
	height: 35px;
	border-radius: 20px;
	padding-bottom: 5px;
	margin-left: 0px;
}


::v-deep(.exSearchTree_search_tip .el-input__wrapper){
	line-height: 35px;
	height: 35px;
}
.exSearchTree_tree_main {
	height: 100%;
	background-image: linear-gradient(rgba(255, 255, 255, 0), rgba(255, 255, 255, 1));
	overflow: auto;
}

/deep/ .el-tree-node {

}


/deep/ .el-tree-node__label {
	font-size: 13px !important;
	font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", 微软雅黑, Arial, sans-serif !important;

}

/*搜索框*/
.exSearch_search_tip {
	line-height: 35px;
	height: 35px;
	border-radius: 8px;
}


.el-tree-node__label {
	width: 80%;
}

.el-tree-node__content {
	height: 28px;
	line-height: 28px;
}

.el-tree-node__content:hover .el-tree-node__label {
	background-color: #d8ebff;
}

.el-tree-node:focus > .el-tree-node__content .el-tree-node__label {
	background-color: #d8ebff;
}

.el-tree-node__expand-icon {
	font-size: 18px;
	padding-top: 4px !important;
	margin-top: -5px;
}

.is-current {
	background-color: rgb(248, 248, 248) !important;

}

.el-tree-node .is-focusable:before {
	content: "";
	display: inline-block;
	position: absolute;
	left: -15px;
	border-left: 1px solid #e5e7ec;
	height: calc(100% + 3px);
}

.custom-tree-node {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: space-between;
	font-size: 14px;
	padding-right: 8px;
}

</style>
